package com.HQCourse.live.service.impl;


import com.HQCourse.Exception.HQCourseException;
import com.HQCourse.client.course.CourseClient;
import com.HQCourse.clilent.userchilent.UserInfoFeignClient;
import com.HQCourse.live.mapper.LiveCourseMapper;
import com.HQCourse.live.service.*;
import com.HQCourse.live.utils.CommonResult;
import com.HQCourse.live.utils.MTCloud;
import com.HQCourse.utils.DateUtil;
import com.alibaba.excel.util.CollectionUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.HQCourse.model.live.*;

import com.example.HQCourse.model.user.UserInfo;
import com.example.HQCourse.model.vod.Teacher;
import com.example.HQCourse.vo.live.LiveCourseConfigVo;
import com.example.HQCourse.vo.live.LiveCourseFormVo;
import com.example.HQCourse.vo.live.LiveCourseGoodsView;
import com.example.HQCourse.vo.live.LiveCourseVo;
import lombok.SneakyThrows;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.temporal.TemporalAccessor;
import java.util.*;

/**
 * <p>
 * 直播课程表 服务实现类
 * </p>
 *
 * @author zww
 * @since 2023-07-13
 */
@Service
public class LiveCourseServiceImpl extends ServiceImpl<LiveCourseMapper, LiveCourse> implements LiveCourseService {
    @Autowired
    private CourseClient client;
    @Autowired
    private MTCloud mtCloud;
    @Autowired
    private LiveCourseDescriptionService liveCourseDescriptionService;
    @Autowired
    private LiveCourseAccountService liveCourseAccountService;
    @Autowired
    private LiveCourseGoodsService liveCourseGoodsService;
    @Autowired
    private LiveCourseConfigService liveCourseConfigService;
    @Autowired
    private UserInfoFeignClient userInfoFeignClient;

    //获取直播配置信息
    @Override
    public LiveCourseConfigVo getCourseConfig(Long id){
        LiveCourseConfig liveCourseConfig=liveCourseConfigService.getCourseConfigCourseId(id);
        LiveCourseConfigVo liveCourseConfigVo1 = new LiveCourseConfigVo();
        if(liveCourseConfigVo1!=null){
          List<LiveCourseGoods> liveCourseGoodsList=liveCourseGoodsService.getGoodsListService(id);
            BeanUtils.copyProperties(liveCourseConfig,liveCourseConfigVo1);
            //封装商品列表
            liveCourseConfigVo1.setLiveCourseGoodsList(liveCourseGoodsList);
        }
        return liveCourseConfigVo1;
    }

    //直播课程分页
    @Override
    public IPage<LiveCourse> selectPage(Page<LiveCourse> coursePage) {
        IPage<LiveCourse> liveCourseIPage = baseMapper.selectPage(coursePage,null);
        List<LiveCourse> records = liveCourseIPage.getRecords();
        for(LiveCourse liveCourse : records) {
            Teacher teacher = client.getTeacherId(liveCourse.getTeacherId());
            liveCourse.getParam().put("teacherName", teacher.getName());
            liveCourse.getParam().put("teacherLevel", teacher.getLevel());
        }
        return liveCourseIPage;
    }
    @Override
    @SneakyThrows
    @Transactional(rollbackFor = {Exception.class})
    public Boolean saveLive(LiveCourseFormVo liveCourseFormVo) {
        LiveCourse liveCourse = new LiveCourse();
        BeanUtils.copyProperties(liveCourseFormVo, liveCourse);
        Teacher teacher = client.getTeacherId(liveCourseFormVo.getTeacherId());
        HashMap<Object, Object> map = new HashMap<>();
        //直播的类型 说明：根据平台开通的直播类型填写 1:教育直播2：生活直播
        map.put("scenes", 2);
        map.put("password", liveCourseFormVo.getPassword());
        String res = null;

            res = mtCloud.courseAdd(liveCourse.getCourseName(),
                    teacher.getId().toString(),
                    new DateTime(liveCourse.getStartTime()).toString("yyyy-MM-dd HH:mm:ss"),
                    new DateTime(liveCourse.getEndTime()).toString("yyyy-MM-dd HH:mm:ss"), teacher.getName(),
                    teacher.getIntro(), map);

            CommonResult<JSONObject> commonResult = JSON.parseObject(res, CommonResult.class);
            if (Integer.parseInt(commonResult.getCode()) == MTCloud.CODE_SUCCESS) {
                JSONObject object = commonResult.getData();
                liveCourse.setCourseId(object.getLong("course_id"));
                baseMapper.insert(liveCourse);

                //保存课程详情信息
                LiveCourseDescription liveCourseDescription = new LiveCourseDescription();
                liveCourseDescription.setDescription(liveCourseFormVo.getDescription());
                liveCourseDescription.setLiveCourseId(liveCourse.getId());
                //添加直播描述信息


                //保存课程账号信息
                LiveCourseAccount liveCourseAccount = new LiveCourseAccount();
                liveCourseAccount.setLiveCourseId(liveCourse.getId());
                liveCourseAccount.setZhuboAccount(object.getString("bid"));
                liveCourseAccount.setZhuboPassword(liveCourseFormVo.getPassword());
                liveCourseAccount.setAdminKey(object.getString("admin_key"));
                liveCourseAccount.setUserKey(object.getString("user_key"));
                liveCourseAccount.setZhuboKey(object.getString("zhubo_key"));
                liveCourseAccountService.save(liveCourseAccount);
            } else {
                String getmsg = commonResult.getmsg();
                throw new HQCourseException(20001, getmsg);
            }
            return true;
    }
    @Override
    public void removeLive(Long id) {
        //删除课程信息
        LiveCourse liveCourse = baseMapper.selectById(id);
        if(liveCourse!=null){
            try {
                mtCloud.courseDelete(liveCourse.getCourseId().toString());
                //删除表中的数据
                baseMapper.deleteById(id);
            } catch (Exception e) {
                e.printStackTrace();
                throw new HQCourseException(20001,"删除直播课程失败");
            }
        }
    }
     //id查询直播课程基本信息和描述信息
    @Override
    public LiveCourseFormVo getLiveCourseFormVo(Long id) {
        //根据id获取直播课程信息
        LiveCourse liveCourse = baseMapper.selectById(id);
        //获取直播课程描述信息
        LiveCourseDescription liveCourseDescription=liveCourseDescriptionService.getLive(id);
        LiveCourseFormVo liveCourseFormVo=new LiveCourseFormVo();
        BeanUtils.copyProperties(liveCourse,liveCourseFormVo);
        liveCourseFormVo.setDescription(liveCourseDescription.getDescription());
        return liveCourseFormVo;
    }
    //更新
    @Override
    public void updateById(LiveCourseFormVo liveCourseVo) {
        Long id = liveCourseVo.getId();
        LiveCourse liveCourse = baseMapper.selectById(id);
        BeanUtils.copyProperties(liveCourseVo,liveCourse);

        Teacher teacher = client.getTeacherId(liveCourseVo.getTeacherId());
//                     *  options 		可选参数
        HashMap<Object, Object> options = new HashMap<>();
        try {
            String res = mtCloud.courseUpdate(liveCourse.getCourseId().toString(),
                    teacher.getId().toString(),
                    liveCourse.getCourseName(),
                    new DateTime(liveCourse.getStartTime()).toString("yyyy-MM-dd HH:mm:ss"),
                    new DateTime(liveCourse.getEndTime()).toString("yyyy-MM-dd HH:mm:ss"),
                    teacher.getName(),
                    teacher.getIntro(),
                    options);
            //返回结果转换，判断是否成功
            CommonResult<JSONObject> commonResult = JSON.parseObject(res, CommonResult.class);
            if(Integer.parseInt(commonResult.getCode()) == MTCloud.CODE_SUCCESS) {
                JSONObject object = commonResult.getData();
                //更新直播课程基本信息
                liveCourse.setCourseId(object.getLong("course_id"));
                baseMapper.updateById(liveCourse);
                //直播课程描述信息更新
                LiveCourseDescription liveCourseDescription =
                        liveCourseDescriptionService.getLive(liveCourse.getId());
                liveCourseDescription.setDescription(liveCourseVo.getDescription());
                liveCourseDescriptionService.updateById(liveCourseDescription);
            } else {
                throw new HQCourseException(20001,"修改直播课程失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    //修改配置
    @Override
    public void updateConfig(LiveCourseConfigVo liveCourseConfigVo) {
        //修改直播配置
        LiveCourseConfig liveCourseConfigVo1 = new LiveCourseConfig();
        BeanUtils.copyProperties(liveCourseConfigVo,liveCourseConfigVo1);
        if(liveCourseConfigVo.getId()==null){
            liveCourseConfigService.save(liveCourseConfigVo1);
        }
        else {
            liveCourseConfigService.updateById(liveCourseConfigVo1);
        }
        //修改直播商品表
        liveCourseGoodsService.remove(new LambdaQueryWrapper<LiveCourseGoods>().eq(LiveCourseGoods::getLiveCourseId, liveCourseConfigVo.getLiveCourseId()));
        if(!CollectionUtils.isEmpty(liveCourseConfigVo.getLiveCourseGoodsList())) {
            liveCourseGoodsService.saveBatch(liveCourseConfigVo.getLiveCourseGoodsList());
        }
        this.updateLifeConfig(liveCourseConfigVo);
    }
    //修改直播平台
    @SneakyThrows
    private void updateLifeConfig(LiveCourseConfigVo liveCourseConfigVo) {
        LiveCourse liveCourse = this.getById(liveCourseConfigVo.getLiveCourseId());

        //参数设置
        HashMap<Object,Object> options = new HashMap<Object, Object>();
        //界面模式
        options.put("pageViewMode", liveCourseConfigVo.getPageViewMode());
        //观看人数开关
        JSONObject number = new JSONObject();
        number.put("enable", liveCourseConfigVo.getNumberEnable());
        options.put("number", number.toJSONString());
        //观看人数开关
        JSONObject store = new JSONObject();
        number.put("enable", liveCourseConfigVo.getStoreEnable());
        number.put("type", liveCourseConfigVo.getStoreType());
        options.put("store", number.toJSONString());
        //商城列表
        List<LiveCourseGoods> liveCourseGoodsList = liveCourseConfigVo.getLiveCourseGoodsList();
        if(!CollectionUtils.isEmpty(liveCourseGoodsList)) {
            List<LiveCourseGoodsView> liveCourseGoodsViewList = new ArrayList<>();
            for(LiveCourseGoods liveCourseGoods : liveCourseGoodsList) {
                LiveCourseGoodsView liveCourseGoodsView = new LiveCourseGoodsView();
                BeanUtils.copyProperties(liveCourseGoods, liveCourseGoodsView);
                liveCourseGoodsViewList.add(liveCourseGoodsView);
            }
            JSONObject goodsListEdit = new JSONObject();
            goodsListEdit.put("status", "0");
            options.put("goodsListEdit ", goodsListEdit.toJSONString());
            options.put("goodsList", JSON.toJSONString(liveCourseGoodsViewList));
        }
        String res = mtCloud.courseUpdateLifeConfig(liveCourse.getCourseId().toString(), options);
        CommonResult<JSONObject> commonResult = JSON.parseObject(res, CommonResult.class);
        if(Integer.parseInt(commonResult.getCode()) != MTCloud.CODE_SUCCESS) {
            throw new HQCourseException(20001,"修改配置信息失败");
        }
    }
    //获取最近的直播
    @Override
    public List<LiveCourseVo> findLatelyList() {
        List<LiveCourseVo> liveCourseVoList=baseMapper.indLatelyList();
        for(LiveCourseVo liveCourseVo : liveCourseVoList) {
            liveCourseVo.setStartTimeString(new DateTime(liveCourseVo.getStartTime()).toString("yyyy年MM月dd HH:mm"));
            liveCourseVo.setEndTimeString(new DateTime(liveCourseVo.getEndTime()).toString("HH:mm"));

            Long teacherId = liveCourseVo.getTeacherId();
            Teacher teacher = client.getTeacherId(teacherId);
            liveCourseVo.setTeacher(teacher);
            liveCourseVo.setLiveStatus(this.getLiveStatus(liveCourseVo));
        }
        return liveCourseVoList;
    }

    /**
     * 直播状态 0：未开始 1：直播中 2：直播结束
     * @param liveCourse
     * @return
     */
    private int getLiveStatus(LiveCourse liveCourse) {
        // 直播状态 0：未开始 1：直播中 2：直播结束
        int liveStatus = 0;
        Date curTime = new Date();
        if(DateUtil.dateCompare(curTime, liveCourse.getStartTime())) {
            liveStatus = 0;
        } else if(DateUtil.dateCompare(curTime, liveCourse.getEndTime())) {
            liveStatus = 1;
        } else {
            liveStatus = 2;
        }
        return liveStatus;
    }
    @SneakyThrows
    @Override  //获取用户access_token
    public JSONObject getAccessTocken(Long id, Long userId) {
        //根据课程id获取直播课程信息
        LiveCourse liveCourse = baseMapper.selectById(id);
        //获取用户信息
        UserInfo userInfo = userInfoFeignClient.getById(userId);
        HashMap<Object, Object> map = new HashMap<>();
        //调用宽拓云的方法

        String s = null;

            s = mtCloud.courseAccess(liveCourse.getCourseId().toString(),
                    userId.toString(),
                    userInfo.getNickName(),
                    MTCloud.ROLE_USER,
                    3600,
                    map);
            CommonResult<JSONObject> commonResult = JSON.parseObject(s, CommonResult.class);
            if (Integer.parseInt(commonResult.getCode()) == MTCloud.CODE_SUCCESS) {
                JSONObject data = commonResult.getData();
                System.out.println("access::" + data.getString("access_token"));
                return data;
            } else {
                throw new HQCourseException(20001, "获取失败");

            }
        }

    @Override
    public Map<String, Object> getInfoById(Long id) {
        LiveCourse liveCourse = this.getById(id);
        liveCourse.getParam().put("startTimeString", new DateTime(liveCourse.getStartTime()).toString("yyyy年MM月dd HH:mm"));
        liveCourse.getParam().put("endTimeString", new DateTime(liveCourse.getEndTime()).toString("HH:mm"));
        Teacher teacher = client.getTeacherId(liveCourse.getTeacherId());
        LiveCourseDescription liveCourseDescription = liveCourseDescriptionService.getById(id);

        Map<String, Object> map = new HashMap<>();
        map.put("liveCourse", liveCourse);
        map.put("liveStatus", this.getLiveStatus(liveCourse));
        map.put("teacher", teacher);
        if(null != liveCourseDescription) {
            map.put("description", liveCourseDescription.getDescription());
        } else {
            map.put("description", "");
        }
        return map;


    }
}

